/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/


///create 125 (5x5x5) dynamic object
#define ARRAY_SIZE_X 5
#define ARRAY_SIZE_Y 5
#define ARRAY_SIZE_Z 5

//maximum number of objects (and allow user to shoot additional boxes)
#define MAX_PROXIES (ARRAY_SIZE_X*ARRAY_SIZE_Y*ARRAY_SIZE_Z + 1024)

///scaling of the objects (0.1 = 20 centimeter boxes )
#define SCALING 1.
#define START_POS_X -5
#define START_POS_Y -5
#define START_POS_Z -3

#include "bulletengine.h"
#include "GlutStuff.h"
///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files.
#include "btBulletDynamicsCommon.h"

#include <stdio.h> //printf debugging

#include "bulletrigidbody.h"
#include "bulletcollisionalgorithm.h"
#include "TriMesh.h"

void BulletRigidBodyEngine::clientMoveAndDisplay()
{
    //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    if(pause) return;

    //simple dynamics world doesn't handle fixed-time-stepping
    float ms = getDeltaTimeMicroseconds();

    ///step the simulation
    if (m_dynamicsWorld)
    {
        m_dynamicsWorld->stepSimulation(ms / 1000000.f);
        //m_dynamicsWorld->stepSimulation(ms / 1000000.f,1,timestep);
//btDynamicsWorld::stepSimulation(btScalar timeStep,int maxSubSteps=1,btScalar fixedTimeStep=btScalar(1.)/btScalar(60.));

        //optional but useful: debug drawing
        //m_dynamicsWorld->debugDrawWorld();
    }

    std::list<RigidBody*>::iterator it = bodies.begin();
    for(;it!=bodies.end();++it)
    {
        BulletRigidBody * b = ((BulletRigidBody*)(*it)->physicsBody);
        btTransform trans;
        b->getMotionState()->getWorldTransform(trans);

        btVector3 p = trans.getOrigin();
        btQuaternion q = trans.getRotation();

        (*it)->position = Math::Vector3(p[0],p[1],p[2]);
        (*it)->orientation = Math::Quaternion(q.getW(),q.getX(),q.getY(),q.getZ());
    }
}

void BulletRigidBodyEngine::initPhysics()
{
    //setTexturing(true);
    //setShadows(true);

    //setCameraDistance(btScalar(SCALING*50.));

    ///collision configuration contains default setup for memory, collision setup
    m_collisionConfiguration = new btDefaultCollisionConfiguration();
    //m_collisionConfiguration->setConvexConvexMultipointIterations();

    ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
    m_dispatcher = new	btCollisionDispatcher(m_collisionConfiguration);
    m_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,BOX_SHAPE_PROXYTYPE,
                                              new BulletCollisionAlgorithm::CreateFunc);

    m_broadphase = new btDbvtBroadphase();

    ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
    btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
    m_solver = sol;

    m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);

    m_dynamicsWorld->setGravity(btVector3(0,gravity,0));


}

void* BulletRigidBodyEngine::createBox(Math::Vector3 &size, Math::Vector3 &position, Math::Quaternion &rotation)
{
    btCollisionShape* boxShape = new btBoxShape(btVector3(btScalar(size.x()),btScalar(size.y()),btScalar(size.z())));
    return addBody(boxShape,position,rotation);
}

void* BulletRigidBodyEngine::createSphere(Math::Real &radius, Math::Vector3 &position)
{
    btCollisionShape* sphereShape = new btSphereShape(radius);
    return addBody(sphereShape,position,Math::Quaternion::IDENTITY);
}

void* BulletRigidBodyEngine::createMesh(TriMesh *mesh, Vector3 &position, Quaternion &rotation)
{
    btTriangleMesh* trimesh = new btTriangleMesh();
    for (int i=0;i<mesh->Faces().size();i++)
    {
        Vector3 v1 = mesh->Faces()[i]->Vertex1()->Position();
        Vector3 v2 = mesh->Faces()[i]->Vertex2()->Position();
        Vector3 v3 = mesh->Faces()[i]->Vertex3()->Position();
        btVector3 btv1(v1.x(),v1.y(),v1.z());
        btVector3 btv2(v2.x(),v2.y(),v2.z());
        btVector3 btv3(v3.x(),v3.y(),v3.z());
        trimesh->addTriangle(btv1,btv2,btv3);
    }
    btCollisionShape* shape = 0;

    //bool useQuantization = true;
    //shape  = new btBvhTriangleMeshShape(trimesh,useQuantization);
    shape = new btConvexTriangleMeshShape(trimesh);
    return addBody(shape,position,rotation);

}

BulletRigidBody* BulletRigidBodyEngine::addBody(btCollisionShape *shape, Math::Vector3 &position, Math::Quaternion &rotation)
{
    m_collisionShapes.push_back(shape);

    btTransform boxTransform;
    boxTransform.setIdentity();
    boxTransform.setRotation(btQuaternion(rotation.x(),rotation.y(),rotation.z(),rotation.w()));
    boxTransform.setOrigin(btVector3(btScalar(position.x()),btScalar(position.y()),btScalar(position.z())));

    //DemoApplication::localCreateRigidBody(0,boxTransform,boxShape);
    {
        btScalar mass(1.);

        btVector3 localInertia(0,0,0);
        shape->calculateLocalInertia(mass,localInertia);

        //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
        btDefaultMotionState* myMotionState = new btDefaultMotionState(boxTransform);
        BulletRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,shape,localInertia);
        BulletRigidBody *body = new BulletRigidBody(rbInfo);

        body->setActivationState(DISABLE_DEACTIVATION);

        body->setRestitution(0.7);
        body->setFriction(0.5);

        //add the body to the dynamics world
        m_dynamicsWorld->addRigidBody(body);
        return body;
    }
}

void	BulletRigidBodyEngine::exitPhysics()
{
    //remove the rigidbodies from the dynamics world and delete them
    int i;
    for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
    {
        btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
        BulletRigidBody* body = BulletRigidBody::upcast(obj);
        if (body && body->getMotionState())
        {
            delete body->getMotionState();
        }
        m_dynamicsWorld->removeCollisionObject( obj );
        delete obj;
    }

    //delete collision shapes
    for (int j=0;j<m_collisionShapes.size();j++)
    {
        btCollisionShape* shape = m_collisionShapes[j];
        delete shape;
    }
    m_collisionShapes.clear();

    delete m_dynamicsWorld;

    delete m_solver;

    delete m_broadphase;

    delete m_dispatcher;

    delete m_collisionConfiguration;
}

void BulletRigidBodyEngine::removeRigidBody(RigidBody* b)
{
    BulletRigidBody *body = (BulletRigidBody*) b->physicsBody;
    m_dynamicsWorld->removeRigidBody(body);

    if (body && body->getMotionState())
    {
        delete body->getMotionState();
    }
    btCollisionShape *shape = body->getCollisionShape();
    m_collisionShapes.remove(shape);
    delete shape;
    m_dynamicsWorld->removeCollisionObject( body );
    delete body;
}


void BulletRigidBodyEngine::setStatic(RigidBody *b, bool set)
{
    if(set)
    {
        BulletRigidBody *bb = (BulletRigidBody*)b->physicsBody;
        bb->setCollisionFlags(bb->getCollisionFlags() | BulletRigidBody::CF_STATIC_OBJECT);
        bb->setMassProps(0,btVector3(0,0,0));
    }
    else
    {
        BulletRigidBody *bb = (BulletRigidBody*)b->physicsBody;
        bb->setCollisionFlags(bb->getCollisionFlags() & !BulletRigidBody::CF_STATIC_OBJECT);
        btVector3 localInertia(0,0,0);
        bb->getCollisionShape()->calculateLocalInertia(1,localInertia);
        bb->setMassProps(1,localInertia);
        //bb->activate(true);
    }
}

void BulletRigidBodyEngine::stop()
{
    std::list<RigidBody*>::iterator it = bodies.begin();
    for(;it!=bodies.end();++it)
    {
        (*it)->position = (*it)->initPosition;
        (*it)->orientation = (*it)->initOrientation;
        BulletRigidBody *bb = (BulletRigidBody*)(*it)->physicsBody;
        //m_dynamicsWorld->removeRigidBody(bb);
        btTransform transform;
        transform.setIdentity();
        transform.setRotation(btQuaternion((*it)->orientation.x(),(*it)->orientation.y(),(*it)->orientation.z(),(*it)->orientation.w()));
        transform.setOrigin(btVector3(btScalar((*it)->position.x()),btScalar((*it)->position.y()),btScalar((*it)->position.z())));

        btMotionState * motion = bb->getMotionState();
        motion->setWorldTransform(transform);
        bb->setMotionState(motion);
        bb->clearForces();
        btVector3 z(0,0,0);
        bb->setAngularVelocity(z);
        bb->setLinearVelocity(z);
        bb->activate(true);

    }

    m_solver->reset();
    m_dynamicsWorld->clearForces();
    m_broadphase->resetPool(m_dispatcher);
    m_clock.reset();


    pause = true;


}

void BulletRigidBodyEngine::setTimestep(Math::Real timestep)
{
    this->timestep = timestep;
}

void BulletRigidBodyEngine::setGravity(Math::Real gravity)
{
    this->gravity = gravity;
    btVector3 g(0,gravity,0);
    m_dynamicsWorld->setGravity(g);
}

void BulletRigidBodyEngine::translateBody(RigidBody* b, Math::Vector3 &t)
{
    BulletRigidBody* bt = (BulletRigidBody*)b->physicsBody;
    btMotionState *ms = bt->getMotionState();
    btTransform trans;
    ms->getWorldTransform(trans);
    trans.setOrigin(btVector3(t.x(),t.y(),t.z()));
    ms->setWorldTransform(trans);
    bt->setMotionState(ms);
    bt->activate(true);
}

